package com.example.iot.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.example.iot.databinding.DialogRfidBinding;

public class RfidDialogFragment extends Fragment {
    private DialogRfidBinding binding;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DialogRfidBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);        // 读取按钮点击事件
        binding.btnRead.setOnClickListener(v -> {
            // 模拟读取新的RFID卡号
            String newRfid = generateRandomRfid();
            binding.tvRfidNumber.setText(newRfid);
            Toast.makeText(requireContext(), "已读取新卡号", Toast.LENGTH_SHORT).show();
        });

        // 确定按钮点击事件
        binding.btnConfirm.setOnClickListener(v -> {
            String rfid = binding.tvRfidNumber.getText().toString();
            Toast.makeText(requireContext(), "已确认卡号：" + rfid, Toast.LENGTH_SHORT).show();
            NavHostFragment.findNavController(this).navigateUp();
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    private String generateRandomRfid() {
        StringBuilder sb = new StringBuilder();
        String chars = "0123456789ABCDEF";
        for (int i = 0; i < 12; i++) {
            sb.append(chars.charAt((int) (Math.random() * chars.length())));
        }
        return sb.toString();
    }

    /**
     * 获取当前显示的RFID号码
     * @return 当前显示的RFID号码，如果binding为null则返回空字符串
     */
    public String getCurrentRfid() {
        return binding != null ? binding.tvRfidNumber.getText().toString() : "";
    }
}
